package org.os.framework.crypto.algorithm;

import lombok.SneakyThrows;

import java.security.MessageDigest;

import org.bouncycastle.util.encoders.Hex;
import org.os.framework.crypto.model.AbstractHash;

/**
 * SAH256
 *
 * @author 魏祖潇
 */
public class Sha256 extends AbstractHash {

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {

        private String salt;

        public Builder salt(String salt) {
            this.salt = salt;
            return this;
        }

        public Sha256 build() {
            return new Sha256(this.salt);
        }

    }

    private static final String ALGORITHM = "SHA-256";

    private String salt;

    public Sha256(String salt) {
        this.salt = null == salt ? "" : salt;
    }

    @SneakyThrows
    @Override
    public String digest(String s) {
        String data = s + salt;
        MessageDigest digest = MessageDigest.getInstance(ALGORITHM);
        digest.update(data.getBytes());
        return Hex.toHexString(digest.digest());
    }

}
